<template>
  <div id="lines" style="width: 630px; height: 250px;"></div>
</template>

<script setup>
import { ref } from "vue";
import { onMounted } from "vue";
import * as echarts from 'echarts';
import userApi from "../../apis/user";

const DrawEcharts = (data, dataY) => {
  console.log("line的data")
  console.log(data);
  var myChart = echarts.init(document.getElementById('lines'));

  // 绘制图表
  myChart.setOption({
    title: {
      text: '商品价格趋势图', // 标题文本
      left: 'center', // 标题位置
    },
    xAxis: {
      type: 'category',
      data: data,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: dataY,
        type: 'line',
        label: {
          show: true,
          formatter: '{c}', // 显示数据值
        },
      },
    ],
  });
}

const getPriceData = async () => {
  try {
    const res = await userApi.getAllProductPrice();
    console.log(res);
    console.log(res.length);
    const types = [];
    const prices = [];
    for (var i = 0; i < res.length; i++) {
      types.push(res[i].type);
      prices.push(Number(res[i].price));
    }
    x.value = types;
    y.value = prices;
    console.log(types);
    console.log(prices);
    console.log(x.value);
    console.log(y.value);
    const dataArray = Object.values(x.value);
    const dataArrayY = Object.values(y.value);
    console.log(dataArray);
    console.log(dataArrayY);
    DrawEcharts(dataArray,dataArrayY);
  } catch (error) {
    console.log(error);
  }
}

onMounted(async () => {
  await getPriceData();
});

const x = ref([]);
const y = ref([]);
</script>

<style scoped>
</style>
